
//
//  SkManager.swift
//  RHello
//
//  Created by 吴智民 on 2020/5/21.
//  Copyright © 2020 Lanchc. All rights reserved.
//

import UIKit
import WebKit
import CocoaAsyncSocket

class SkManager: NSObject {
    
    static private let KK_LOCAK_IP: String = "KK_LOCAK_IP#LANCHC"
    
    static let `default` = SkManager()
    
    
    weak var tx: UITextView?
    
    weak var wb: WKWebView?
    
    var hsip: String = ""
    var prot: String = ""
    
    /**连接实例*/
    lazy var clientSocket: GCDAsyncSocket = {
        let c = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
        return c
    }()
    
    func scanningIp() {
        
        for i in 1 ..< 255 {
            let temp_ip: String = "192.168.1.\(i)"
            showMessage("sanning ip => \(temp_ip)")
            try? SkManager.default.clientSocket.connect(toHost: temp_ip, onPort: UInt16(2001), withTimeout: 10)
        }
    }
    
    // 读取链接地址
    func askCurrentLinkIp() -> String {
        return UserDefaults.standard.string(forKey: SkManager.KK_LOCAK_IP) ?? ""
    }
    
    // 写入链接地址
    func writeInLinkIp(hostURL: String) -> Void {
        UserDefaults.standard.setValue(hostURL, forKey: SkManager.KK_LOCAK_IP)
        UserDefaults.standard.synchronize()
        print("保存写入地址成功 => \(hostURL)")
    }
    
}



extension SkManager: GCDAsyncSocketDelegate {
    
    
    /// 链接成功
    func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
        
        
        showMessage("链接成功！")
        
        let address = "Server IP：" + "\(host)"
        /// 保存ip
        SkManager.default.writeInLinkIp(hostURL: host)
        
        showMessage(address)
        
        clientSocket.readData(withTimeout: -1, tag: 0)
    }
    
    /// 接受消息
    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
        
        let text = String(data: data, encoding: .utf8)
        
        showMessage(text!)
        
        clientSocket.readData(withTimeout: -1, tag: 0)
    }
    /// 断开链接
    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
        
        showMessage("断开链接")
    }
    
    func sendMessage(bc: String) {
        // tag: message tag
        clientSocket.write( bc.data(using: .utf8), withTimeout: -1, tag: 0)
    }
    
    // 现实消息
    func showMessage(_ str: String) {
        guard let txt = tx else { return  }
        txt.text = txt.text.appendingFormat("%@\n", str)
    }
    

    func loadURL() {
        let tempNext: String = UserDefaults.standard.string(forKey: SkManager.KK_LOCAK_IP) ?? ""
        let tempHost: String = hsip.isEmpty ? tempNext : hsip
        guard let xURL = URL(string: "http://\(tempHost):8080/?action=stream") else { return }
        
        wb?.load(URLRequest(url: xURL))
    }
}
